#!coding:utf8
"""
Created on June 20, 2013

@author: join
"""
from datetime import datetime
import os
import cPickle
from rest_framework.response import Response
import rsa
from cvirt.manager.views import NonModelBaseAPIView
from cvirt.common import utils
from cvirt.manager.models import Instance


class License(NonModelBaseAPIView):
    def get(self, request, *args, **kwargs):
        try:
            with file("/etc/licenseinfo") as key:
                licenseinfo = self._decrypt_license(key.read())
        except:
            result = {"status": 1, "msg": "系统尚未认证，请填写序列号"}
            return Response(result)

        #just check time period
        if licenseinfo['time'] != -1 and datetime.now().date() > licenseinfo['time']:
            result = {"satus": 2, "msg": "序列号已过期"}
        if license['hardwareid'] != utils.hardware_uuid():
            return Response({"msg": "不识别的硬件设备"})
        insts = Instance.objects.all()
        available = license["inst"] - len(insts)
        if available <= 0:
            return Response({"msg": "非法序列号"})
        else:
            result = {"satus": 0, "msg": "ok"}
        return Response(result)

    def _decrypt_license(self, emsg):
        dmsg = rsa.transform.binascii.a2b_hex(emsg)
        with file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tcloudpriv')) as prikeyfile:
            dmsg = rsa.decrypt(dmsg, rsa.PrivateKey.load_pkcs1(prikeyfile.read()))
        return cPickle.loads(dmsg)
